package com.cn.kabalifemerchants.ui.login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cn.kabalifemerchants.R;
import com.cn.kabalifemerchants.base.IBaseActivity;
import com.cn.kabalifemerchants.callback.SchedulerTransformer;
import com.cn.kabalifemerchants.config.LoginHelper;
import com.cn.kabalifemerchants.event.RxBus;
import com.cn.kabalifemerchants.event.RxBusBean;
import com.cn.kabalifemerchants.ui.MainActivity;
import com.cn.kabalifemerchants.ui.login.bean.AgreementBean;
import com.cn.kabalifemerchants.ui.login.bean.LoginBean;
import com.cn.kabalifemerchants.ui.login.bean.MsgBean;
import com.cn.kabalifemerchants.ui.login.bean.RegisterBean;
import com.cn.kabalifemerchants.ui.user.bean.MyUserInfoBean;
import com.cn.kabalifemerchants.utils.LoggerUtils;
import com.cn.kabalifemerchants.utils.RxToast;
import com.cn.kabalifemerchants.utils.SPUtil;
import com.cn.kabalifemerchants.utils.SoftHideKeyBoardUtil;
import com.cn.kabalifemerchants.utils.VersionUtils;
import com.cn.kabalifemerchants.utils.WebViewHtmlUtils;
import com.cn.kabalifemerchants.view.PhoneCode;
import com.cn.kabalifemerchants.view.dialogView.AgeDialog;
import com.flyco.roundview.RoundTextView;
import com.zzhoujay.richtext.RichText;

import butterknife.BindView;
import butterknife.OnClick;
import rx.functions.Action1;

/**
 * Created by 晓林 on 2020/9/2.
 * function:
 */
public class LoginActivity extends IBaseActivity<LoginView, LoginPresenter> implements LoginView {
    @BindView(R.id.tv_btn_login)
    TextView tvBtnLogin;
    @BindView(R.id.et_login_phone)
    EditText etLoginPhone;
    @BindView(R.id.et_login_pwd)
    EditText etLoginPwd;
    @BindView(R.id.tv_pwd_xian)
    TextView tvPwdXian;
    @BindView(R.id.tv_btn_code)
    RoundTextView tvBtnCode;
    @BindView(R.id.ll_btn_quick)
    LinearLayout llBtnQuick;

    @BindView(R.id.tv_btn_pwd_login)
    RoundTextView tvBtnPwdLogin;
    @BindView(R.id.tv_btn_login_type)
    TextView tvBtnLoginType;
    @BindView(R.id.img_btn_login_wx)
    ImageView imgBtnLoginWx;
    @BindView(R.id.img_btn_login_qq)
    ImageView imgBtnLoginQq;
    @BindView(R.id.ll_login_phone)
    LinearLayout llLoginPhone;
    @BindView(R.id.et_phone_code)
    PhoneCode etPhoneCode;
    @BindView(R.id.tv_btn_code_re)
    RoundTextView tvBtnCodeRe;
    @BindView(R.id.ll_login_code)
    LinearLayout llLoginCode;
    @BindView(R.id.ll_login_pwd)
    LinearLayout llLoginPwd;

    @BindView(R.id.fl_login)
    FrameLayout flLogin;
    @BindView(R.id.fl_register)
    FrameLayout flRegister;
    @BindView(R.id.et_register_y_code)
    EditText etRegisterYCode;
    @BindView(R.id.et_register_phone)
    EditText etRegisterPhone;
    @BindView(R.id.et_register_code)
    EditText etRegisterCode;
    @BindView(R.id.tv_btn_register_code)
    RoundTextView tvBtnRegisterCode;
    @BindView(R.id.et_register_pwd)
    EditText etRegisterPwd;
    @BindView(R.id.et_register_pwd_to)
    EditText etRegisterPwdTo;
    @BindView(R.id.img_check)
    ImageView imgCheck;
    @BindView(R.id.tv_phone_code_su)
    TextView tv_phone_code_su;


    int checkImg = 0; //协议是否选中

    int signMsg = 1;//1是登录。2的注册
    MyCountDownTimer myCountDownTimer;


    int signLib = 1;//1是正常登录 2是第三方登录
    int LoginLibId = -1;//第三方登录的id

    String phone;//手机号

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }


    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        SoftHideKeyBoardUtil.assistActivity(this);
        myCountDownTimer = new MyCountDownTimer(60000, 1000);
        etPhoneCode.setOnInputListener(new PhoneCode.OnInputListener() {
            @Override
            public void onSucess(String code) {
                LoggerUtils.e("验证码:" + code);
                hideKeyboard(etPhoneCode);
                if (signLib == 1) {
                    //正常登錄
                    mPresenter.onLoginData(
                            phone,
                            code,
                            2);
                } else {
                    //第三方登录
//                    if (LoginLibId > 0)
//                        mPresenter.onBindingPhoneData(
//                                phone,
//                                code, LoginLibId
//                        );
                }
            }

            @Override
            public void onInput() {

            }
        });

        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean.class)
                .compose(new SchedulerTransformer<RxBusBean>())
                .subscribe(new Action1<RxBusBean>() {
                    @SuppressLint("WrongConstant")
                    @Override
                    public void call(RxBusBean rxBusBean) {
                        if (rxBusBean.getId() == 1111 && rxBusBean.getSign() == 1111) {
                            imgCheck.setImageResource(R.drawable.check_false);
                            checkImg = 0;
                        }else  if (rxBusBean.getId() == 1112 && rxBusBean.getSign() == 1112) {
                            imgCheck.setImageResource(R.drawable.check_true);
                            checkImg = 1;
                        }
                    }
                });
        //mPresenter.onAgreementData(5);
    }

    @OnClick({R.id.tv_btn_fanhui, R.id.tv_btn_register, R.id.img_check, R.id.tv_btn_agreement, R.id.tv_btn_register_code, R.id.tv_register, R.id.tv_btn_login, R.id.tv_btn_code, R.id.tv_btn_quick_login, R.id.tv_btn_retrieve_pwd, R.id.tv_btn_pwd_login, R.id.tv_btn_login_type, R.id.img_btn_login_wx, R.id.img_btn_login_qq, R.id.tv_btn_code_re})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_btn_fanhui:
                llLoginPhone.setVisibility(View.VISIBLE);
                llLoginCode.setVisibility(View.GONE);
                break;
            case R.id.tv_btn_register:
                //todo  左上角注册切换
                flLogin.setVisibility(View.GONE);
                flRegister.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_btn_login:
                //todo 右上角 登录按钮
                flLogin.setVisibility(View.VISIBLE);
                flRegister.setVisibility(View.GONE);
                break;
            case R.id.tv_btn_code:
                //todo 获取验证码
                if (!TextUtils.isEmpty(etLoginPhone.getText().toString().trim())) {
                    signMsg = 1;
                    myCountDownTimer.cancel();
                    mPresenter.onPhoneCodeData(etLoginPhone.getText().toString().trim(), 1);
                } else RxToast.error("请输入手机号码");
//
                break;
            case R.id.tv_btn_retrieve_pwd:
                //todo 找回密码
                $startActivity(ForgetPwdActivity.class);
                break;
            case R.id.tv_btn_quick_login:
                //todo 快捷登录。切换
                llLoginPwd.setVisibility(View.GONE);
                tvPwdXian.setVisibility(View.GONE);
                llBtnQuick.setVisibility(View.GONE);
                tvBtnCode.setVisibility(View.VISIBLE);
                tvBtnPwdLogin.setVisibility(View.GONE);
                tvBtnLoginType.setVisibility(View.VISIBLE);
                break;
            case R.id.tv_btn_pwd_login:
                //todo 密码登录
                if (!TextUtils.isEmpty(etLoginPhone.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(etLoginPwd.getText().toString().trim())) {
                        mPresenter.onLoginData(
                                etLoginPhone.getText().toString().trim(),
                                etLoginPwd.getText().toString().trim(),
                                1);
                    } else RxToast.error("请输入登录密码");
                } else RxToast.error("请输入手机号码");
                break;
            case R.id.tv_btn_login_type:
                //todo  账号密码登录 切換
                llLoginPwd.setVisibility(View.VISIBLE);
                tvPwdXian.setVisibility(View.VISIBLE);
                llBtnQuick.setVisibility(View.VISIBLE);
                tvBtnCode.setVisibility(View.GONE);
                tvBtnPwdLogin.setVisibility(View.VISIBLE);
                tvBtnLoginType.setVisibility(View.GONE);
                break;
            case R.id.img_btn_login_wx:
                //todo 微信
                boolean isWx = VersionUtils.isWxInstall(this);
                if (isWx) {
                    getWx();
                } else {
                    RxToast.error("您暂未安装微信客户端");
                }
                break;
            case R.id.img_btn_login_qq:
                //todo qq
                boolean isQQ = VersionUtils.isQQClientAvailable(this);
                if (isQQ) {
                    getQQ();
                } else {
                    RxToast.error("您暂未安装QQ客户端");
                }
                break;
            case R.id.tv_btn_code_re:
                //todo 重新 获取验证码
                if (!TextUtils.isEmpty(etLoginPhone.getText().toString().trim())) {
                    signMsg = 1;
                    myCountDownTimer.cancel();
                    mPresenter.onPhoneCodeData(etLoginPhone.getText().toString().trim(), 1);
                } else RxToast.error("请输入手机号码");
                break;

            case R.id.tv_btn_register_code:
                //todo 注册 获取的 获取验证码
                if (!TextUtils.isEmpty(etRegisterPhone.getText().toString().trim())) {
                    signMsg = 2;
                    myCountDownTimer.cancel();
                    mPresenter.onPhoneCodeData(etRegisterPhone.getText().toString().trim(), 1);
                } else RxToast.error("请输入手机号码");

                break;
            case R.id.img_check:
                //todo 同意 check
//                if (checkImg == 1) {
//                    imgCheck.setImageResource(R.drawable.check_false);
//                    checkImg = 0;
//                } else {
//                    imgCheck.setImageResource(R.drawable.check_true);
//                    checkImg = 1;
//                }
                Bundle bundle = new Bundle();
                bundle.putInt("sign", 1);
                $startActivity(AgreementActivity.class, bundle);
                break;
            case R.id.tv_btn_agreement:
                //todo 协议
                 bundle = new Bundle();
                bundle.putInt("sign", 1);
                $startActivity(AgreementActivity.class, bundle);
                break;
            case R.id.tv_register:
                //todo 注册
                if (!TextUtils.isEmpty(etRegisterPhone.getText().toString().trim())) {
                    if (!TextUtils.isEmpty(etRegisterCode.getText().toString().trim())) {
                        if (!TextUtils.isEmpty(etRegisterPwd.getText().toString().trim())) {
                            if (etRegisterPwd.getText().toString().trim().equals(etRegisterPwdTo.getText().toString().trim())) {
                                if (checkImg == 1) {
                                    mPresenter.onRegisterData(
                                            etRegisterPhone.getText().toString().trim(),
                                            etRegisterPwd.getText().toString().trim(),
                                            etRegisterCode.getText().toString().trim(),
                                            etRegisterYCode.getText().toString().trim());
                                } else RxToast.error("请同意注册协议");
                            } else RxToast.error("两次输入密码错误");
                        } else RxToast.error("请输入登录密码");
                    } else RxToast.error("请输入验证码");
                } else RxToast.error("请输入手机号码");
                break;

        }
    }

    private void getQQ() {
//        UMShareConfig config = new UMShareConfig();
//        config.isNeedAuthOnGetUserInfo(true);
//        UMShareAPI.get(this).setShareConfig(config);
//        UMShareAPI.get(getMe()).getPlatformInfo(this, SHARE_MEDIA.QQ, new UMAuthListener() {
//            @Override
//            public void onStart(SHARE_MEDIA share_media) {
//            }
//
//            @Override
//            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                String jsonStr = GsonUtil.mapToJsonStr(map);
////                mapLib = map;
//                LoggerUtils.d("QQ成功返回用户数据：" + jsonStr);
////                signLogin = 2;
////                //检查是否注册
////                HashMap<String, Object> maps = new HashMap<>();
////                maps.put("openid", map.get("openid"));
////                maps.put("thirdPartyType", Constants.LOGIN_TYPE_2);
////                mPresenter.onLoginCheckData(GsonUtil.mapToJsonStrObj(maps));
//
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
//                RxToast.error("失败" + throwable.getMessage() + "错误码" + i);
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA share_media, int i) {
//            }
//        });
    }

    private void getWx() {
//        UMShareConfig config = new UMShareConfig();
//        config.isNeedAuthOnGetUserInfo(true);
//        UMShareAPI.get(this).setShareConfig(config);
//        UMShareAPI.get(getMe()).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
//            @Override
//            public void onStart(SHARE_MEDIA share_media) {
//            }
//
//            @Override
//            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
//                String jsonStr = GsonUtil.mapToJsonStr(map);
//                LoggerUtils.d("微信成功返回用户数据：" + jsonStr);
////                String openid, String nickname, String head, int type, int sex
//                mPresenter.onLoginLibData(map.get("openid"),
//                        map.get("screen_name"),
//                        map.get("iconurl"), 1, map.get("openid").toString().equals("男") ? 1 : 2
//                );
//                //检查是否注册
////                HashMap<String, Object> maps = new HashMap<>();
////                maps.put("openid", map.get("openid"));
////                maps.put("thirdPartyType", Constants.LOGIN_TYPE_1);
////                mPresenter.onLoginCheckData(GsonUtil.mapToJsonStrObj(maps));
//
//            }
//
//            @Override
//            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
//                RxToast.error("失败" + throwable.getMessage() + "错误码" + i);
//            }
//
//            @Override
//            public void onCancel(SHARE_MEDIA share_media, int i) {
//            }
//        });
    }

    @Override
    public void onReLoggedIn(String msg) {

    }

    @Override
    public void onError(String msg) {

        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onPhoneCodeSuccess(MsgBean bean) {

        RxToast.success(bean.getMsg());
        if (signMsg == 1) {
            llLoginPhone.setVisibility(View.GONE);
            llLoginCode.setVisibility(View.VISIBLE);
            hideKeyboard(etLoginPhone);
            phone = etLoginPhone.getText().toString().trim();
            tv_phone_code_su.setText("已发送到: " + etLoginPhone.getText().toString().trim());

        } else {
            //注册
            myCountDownTimer.start();
        }
    }

    @Override
    public void onLoginSuccess(LoginBean bean) {
        //登录之后。、判断是否审核通过。
        boolean is = SPUtil.saveObjectToShare(LoginHelper.USER_LOGIN, bean);
        if (is)
            mPresenter.onUserInfoData(bean.getResult());

    }

    @Override
    public void onRegisterSuccess(RegisterBean bean) {
        RxToast.success(bean.getMsg());
        mPresenter.onLoginData(
                etRegisterPhone.getText().toString().trim(),
                etRegisterPwd.getText().toString().trim(),
                1);
    }

    @Override
    public void onUserInfoSuccess(MyUserInfoBean bean) {
        if (bean.getResult().getBusiness().getIs_check() == 0) {
            //
            //跳转审核，
            $startActivity(CooperationActivity.class);
        }else   if (bean.getResult().getBusiness().getIs_check() == 1) {
            boolean is = SPUtil.saveObjectToShare(LoginHelper.USER_USER, bean);
            if (is) {
                SPUtil.saveString(LoginHelper.ISLOGIN, "1");
                $startActivityFinish(MainActivity.class);
            }
        } else {
           RxToast.success("您的申请已在审核中");
        }
    }

    @Override
    public void onAgreementSuccess(AgreementBean bean) {
        if (!LoginHelper.isAge()) {
            AgeDialog ageDialog=new AgeDialog(getMe());
            if (!TextUtils.isEmpty(bean.getResult())) {
                StringBuilder sb = new StringBuilder();
                sb.append(WebViewHtmlUtils.getHtmlData(bean.getResult()));
                ageDialog.getWebView().loadDataWithBaseURL(null, sb.toString(), "text/html", "utf-8", null);//加载html数据
            }
            ageDialog.getTv_btn_n().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ageDialog.dismiss();
                    finish();
                }
            });
            ageDialog.getTv_btn_y().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ageDialog.dismiss();
                }
            });
            ageDialog.show();
        }
    }

//    @Override
//    public void onLoginLibSuccess(LoginLibBean bean) {
//        LoginLibId = bean.getResult().getId();
//        //第三方登录
//        if (bean.getResult().isHave_phone()) {
//            LoginBean loginBean = new LoginBean();
//            loginBean.setResult(bean.getResult().getToken());
//            boolean is = SPUtil.saveObjectToShare(LoginHelper.USER_LOGIN, loginBean);
//            if (is) {
//                SPUtil.saveString(LoginHelper.ISLOGIN, "1");
//                $startActivityFinish(MainActivity.class);
//            }
//        } else {
//            RxToast.success("请绑定手机号");
//            signLib = 2;
//            llLoginPwd.setVisibility(View.GONE);
//            tvPwdXian.setVisibility(View.GONE);
//            llBtnQuick.setVisibility(View.GONE);
//            tvBtnCode.setVisibility(View.VISIBLE);
//            tvBtnPwdLogin.setVisibility(View.GONE);
//            tvBtnLoginType.setVisibility(View.VISIBLE);
//        }
//    }


    /**
     * 倒计时函数
     */
    private class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        //计时过程
        @Override
        public void onTick(long l) {
            //防止计时过程中重复点击
            if (signMsg == 1) {

                tvBtnCodeRe.setClickable(false);
                tvBtnCodeRe.setText(l / 1000 + getResources().getString(R.string.time_second_str));
            } else {
                tvBtnRegisterCode.setClickable(false);
                tvBtnRegisterCode.setText(l / 1000 + getResources().getString(R.string.time_second_str));
            }
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //设置可点击
            if (signMsg == 1) {
                tvBtnCodeRe.setText(getResources().getString(R.string.time_again_str));
                tvBtnCodeRe.setClickable(true);
            } else {
                tvBtnRegisterCode.setText(getResources().getString(R.string.time_again_str));
                tvBtnRegisterCode.setClickable(true);
            }

        }
    }
}
